package com.mhl.adapter;

import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.mhl.campuscabinet.R;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.SoldProduct;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

// 预约但还没有交付的订单信息
public class WaitSoldProductAdapter extends RecyclerView.Adapter<WaitSoldProductAdapter.ViewHolder> {
    //展示的未交付订单的实体List
    private List<SoldProduct> mOrderList;
    private AppCompatActivity activity;
    private int itemId;


    // 内部静态类负责对已加载的商品布局信息进行缓存
    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView productImage;
        TextView productName;
        TextView solder;
        TextView buyer;
        TextView complete;

        public ViewHolder(View view) {
            super(view);
            productImage = view.findViewById(R.id.product_image);
            productName = view.findViewById(R.id.product_name);
            buyer = view.findViewById(R.id.buyer_name);
            solder = view.findViewById(R.id.solder_name);
            complete = view.findViewById(R.id.complete);
        }
    }

    // 构造方法
    public WaitSoldProductAdapter(List<SoldProduct> orderList, AppCompatActivity activity) {
        this.activity = activity;
        mOrderList = orderList;
    }

    @NonNull
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.wait_item, parent, false);
        WaitSoldProductAdapter.ViewHolder holder = new WaitSoldProductAdapter.ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull WaitSoldProductAdapter.ViewHolder holder, int position) {
        SoldProduct soldProduct = mOrderList.get(position);
        itemId = mOrderList.get(position).getItemId();
        Glide.with(activity).load(soldProduct.getUrls().get(0)).into(holder.productImage);
        holder.productName.setText(soldProduct.getName());
        holder.solder.setText(soldProduct.getSolder());
        holder.buyer.setText(soldProduct.getBuyer());
        holder.complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 向服务器发送更改交易进度请求

                // 从本窗口移除该已交易的曾未交易订单视图


                JSONObject req = new JSONObject();

                try {
                    MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                    req.put("merchandise_id", itemId);
                    String json = req.toString();
                    RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

                    OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "merchandise/finish", requestBody, new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            System.out.println(e);
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            final String resString = response.body().string();
                            int state = 1;
                            try {
                                JSONObject errcodeJson = new JSONObject(resString);
                                state = errcodeJson.getInt("errcode");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            Looper.prepare();
                            if (state != 0) {
                                Toast.makeText(activity, "Finish failed", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(activity, "Finish succeeded", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();

                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        mOrderList.remove(soldProduct);
                        notifyDataSetChanged();
                    }
                });
            }
        });
    }

    @Override
    public int getItemCount() {
        return mOrderList.size();
    }

}
